import 'package:pacsun/model/taskModel.dart';
import 'package:pacsun/view/create/guide_dialog.dart';

// -------------------------------------------------------------------------
import 'package:pacsun/view/task/task_page.dart' show TaskPage;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:showcaseview/showcaseview.dart';

import '../../provider/taskListProv.dart';
import '../../provider/userProv.dart';
import '../../utils/utils.dart';
import '../task/task_detail_page.dart';
import '../task/theme/app_colors.dart';
import '../task/widgets/cache_network_image.dart';
import '../task/widgets/task_card.dart';
import '../user/userProfile.dart';
import '../../utils/frontBottomSheet.dart';
import 'createBecomeCreator.dart';
import 'package:pacsun/view/create/mediaPicker/mediaPickerPage.dart';

// -------------------------------------------------------------------------
class CreateTasks extends StatefulWidget {
  final GlobalKey guideKey;
  const CreateTasks({super.key, required this.guideKey});

  @override
  State<CreateTasks> createState() => _CreateTasksState();
}

class _CreateTasksState extends State<CreateTasks> {
  final logger = Logger();
  late final TaskListProv _taskListProv;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _taskListProv = Provider.of<TaskListProv>(context, listen: false);
      _taskListProv.setAid(context.read<UserProvider>().currentUser!.aid!);
      _initData();
    });
  }

  Future<void> _initData() async {
    try {
      _taskListProv.getCategoryList();
    } catch (e) {
      logger.e('_initData----$e}');
    }
  }

  @override
  void dispose() {
    _taskListProv.claerAll();
    super.dispose();
  }

  void onRefresh() {
    _taskListProv.refreshCurrentCategory();
  }

  void onLoadMore() {
    _taskListProv.loadMoreCurrentCategory();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextBreakLine(guideKey: widget.guideKey),
        _buildHorizontalBlock()
      ],
    );
  }

  Widget _buildHorizontalBlock() {
    return Consumer<TaskListProv>(builder: (context, taskListProv, child) {
      return MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling),
        child: Container(
          margin: EdgeInsets.only(left: 16.w, right: 16.w),
          child: SizedBox(
            width: MediaQuery.of(context).size.width,
            height: 330.h,
            child: NotificationListener<ScrollNotification>(
              onNotification: (ScrollNotification scrollInfo) {
                if (scrollInfo.metrics.pixels ==
                        scrollInfo.metrics.maxScrollExtent &&
                    taskListProv.currentCategory.hasMore) {
                  logger.w('加载更多');
                  onLoadMore();
                  return true;
                }
                return false;
              },
              child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true, // 让内部 ListView 自适应内容高度
                  itemExtent: 320.w,
                  itemCount: taskListProv.getTaskList().length,
                  itemBuilder: (context, index) {
                    return _buildVerticalBlock(
                        taskListProv.getTaskList()[index]);
                  }),
            ),
          ),
        ),
      );
    });
  }

  Widget _buildVerticalBlock(List<TaskModal> items) {
    return SizedBox(
      height: 330.h,
      width: 320.w,
      child: ListView.builder(
          padding: EdgeInsets.zero,
          physics: NeverScrollableScrollPhysics(),
          scrollDirection: Axis.vertical,
          // 横向滚动
          itemCount: items.length,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: () {
                String diffTimeStr = formatUSTimeDiff(items[index].endDate);
                bool isExpired = diffTimeStr.contains('-');
                jumpPage(context, items[index], isExpired);
              },
              // child: _itemBlock(items[index], index),
              child: TaskCard(
                  task: items[index],
                  type: 'ACTIVE',
                  fromType: 0,
                  index: index),
            );
          }),
    );
  }

  Widget _itemBlock(TaskModal item, index) {
    return Card(
      elevation: .5,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: Container(
        width: 320.w,
        padding: const EdgeInsets.only(left: 13, right: 13, top: 8, bottom: 8),
        decoration: index == 0
            ? _boxDecoration1()
            : index == 1
                ? _boxDecoration2()
                : _boxDecoration3(),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            CacheNetworkImage(
              imageUrl: item.bannerUrl,
              width: 46.w,
              height: 46.h,
              borderRadius: 4.r,
            ),
            SizedBox(
              width: 8.w,
            ),
            Expanded(
              child: _buildActiveCenter(item),
            ),
            _buildActiveRight(item)
          ],
        ),
      ),
    );
  }

  // Active 任务中间内容
  Widget _buildActiveCenter(TaskModal task) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(task.taskName,
            style: customTextStyle(
              fontSize: 14,
              overflow: TextOverflow.ellipsis,
              height: 1.2,
            ),
            maxLines: 1,
            softWrap: true),
        Text(
          task.description,
          style: customTextStyle(
              overflow: TextOverflow.ellipsis, opacity: 0.4, height: 1.4),
          maxLines: 1,
        ),
        const SizedBox(height: 5),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            task.platformIconUrl.isNotEmpty
                ? Padding(
                    padding: const EdgeInsets.only(right: 5),
                    child: Builder(
                      builder: (context) {
                        return CacheNetworkImage(
                          imageUrl: task.platformIconUrl,
                          imageType: ImageType.asset,
                          width: 12.w,
                          height: 12.h,
                          borderRadius: 4.r,
                        );
                      },
                    ),
                  )
                : const SizedBox.shrink(),
            Text(
              task.endDateStr,
              style: customTextStyle(opacity: 0.3),
            ),
          ],
        ),
      ],
    );
  }

  // Active 任务右侧内容
  Widget _buildActiveRight(TaskModal task) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        if (task.taskReward.isNotEmpty && task.taskReward['cmp'] != null) ...[
          Text('+${task.taskReward['cmp']}',
              style: customTextStyle(
                fontSize: 18,
                fontWeight: 600,
                color: task.taskReward['type'] == 'money'
                    ? FamilyTextColor.money
                    : FamilyTextColor.points,
              )),
          SizedBox(width: 6),
          SvgPicture.asset(
            task.taskReward['type'] == 'money'
                ? 'assets/icons/icon_money1.svg'
                : 'assets/icons/icon_points.svg',
            width: 16.w,
            height: 16.w,
          ),
        ]
      ],
    );
  }

  BoxDecoration _boxDecoration1() {
    return BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [
          const Color(0xFF66502B),
          const Color(0xFF66502B).withAlpha(204),
          const Color(0xFF222222).withAlpha(153),
          const Color(0xFF222222).withAlpha(204),
          const Color(0xFF222222),
        ],
        stops: const [0, 0.3, 0.5, 0.7, 1],
      ),
    );
  }

  BoxDecoration _boxDecoration2() {
    return BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [
          const Color.fromRGBO(115, 30, 62, 1),
          const Color.fromRGBO(115, 30, 62, .8),
          const Color.fromRGBO(34, 34, 34, .8),
          const Color.fromRGBO(34, 34, 34, .9),
          const Color.fromRGBO(34, 34, 34, 1),
        ],
        stops: const [0, 0.3, 0.5, 0.7, 1],
      ),
    );
  }

  BoxDecoration _boxDecoration3() {
    return BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [
          const Color.fromRGBO(32, 52, 90, 1),
          const Color.fromRGBO(32, 52, 90, 1),
          const Color.fromRGBO(34, 34, 34, .8),
          const Color.fromRGBO(34, 34, 34, .9),
          const Color.fromRGBO(34, 34, 34, 1),
        ],
        stops: const [0, 0.3, 0.5, 0.7, 1],
      ),
    );
  }
}

class TextBreakLine extends StatelessWidget {
  final GlobalKey guideKey;
  final VoidCallback? onMorePressed;

  const TextBreakLine({super.key, this.onMorePressed, required this.guideKey});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: 15.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'TASKS',
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w700,
              fontSize: 20,
              letterSpacing: 0,
            ),
          ),
          GestureDetector(
            onTap: onMorePressed ??
                () {
                  // Default navigation action if none provided
                  Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => TaskPage(),
                  ));
                },
            child: Showcase.withWidget(
              key: guideKey,
              height: 114.5.h,
              width: 319.w,
              tooltipPosition: TooltipPosition.top,
              disableBarrierInteraction: true,
              container: NewGuideDialog(
                index: 3,
                onTop: () => ShowCaseWidget.of(context).next(),
              ),
              child: Container(
                width: 138.w,
                height: 25.h,
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(217, 217, 217, 0.2),
                  borderRadius: BorderRadius.circular(12.5.h),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // "GO TO TASK PLAZA" Text
                    Text(
                      'GO TO TASK PANEL',
                      style: TextStyle(
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w400,
                        fontSize: 12.sp,
                        height: 1.0,
                        letterSpacing: 0,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(width: 5.w),
                    // Button with -45deg angle
                    Image.asset(
                      'assets/icons/icon_arrow_forward.png',
                      width: 12.w,
                      height: 12.h,
                      color: Color.fromRGBO(255, 255, 255, 0.2),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

void jumpPage(context, TaskModal task, bool isExpired) {
  // taskrecordid 任务到my Task 后的id
  // taskconfigid 任务原始id
  Widget page;
  // 新手任务并且已完成才提示
  if (task.status == 'ENDED' && task.taskType == 'BEGINNER_TASK') {
    Fluttertoast.showToast(
        msg: 'Completed',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Color(0XFF444444).withOpacity(0.8));
  } else if (task.taskCode == 'SET_CENTER_PAGE') {
    Fluttertoast.showToast(
        msg: 'Function under development',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Color(0XFF444444).withOpacity(0.8));
  } else if (isExpired) {
    Fluttertoast.showToast(
        msg: 'The Task Has Expired',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Color(0XFF444444).withOpacity(0.8));
    return;
  } else {
    switch (task.taskCode) {
      // 注册创作者
      case 'REGISTER_TASK':
        page = BecomeCreator(sourceIndex: 2);
        break;
      // 社媒主页添加社区主页
      // case 'ADD_COMMUNITY_HOMEPAGE':
      //   page = UserProfile(taskId: task.id);
      //   break;
      case 'ADD_COMMUNITY_HOMEPAGE':
        showStoreFrontBottomSheet(context, task.id);
        return; // Important to return here

      // 完善个人资料
      case 'SET_HOMEPAGE':
        page = UserProfile(taskId: task.id);
        break;
      // 发布第一个帖子
      case 'FIRST_PUBLISH':
        page = MediaPickerPage(taskConfigId: task.id);
        break;
      default:
        page = TaskDetailPage(
          taskId: task.taskrecordid ?? task.id,
          taskType: task.taskrecordid != null ? 'My Tasks' : task.taskType,
        );
        break;
    }
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => page,
      ),
    );
  }
}

class NewSummerArrive extends StatelessWidget {
  const NewSummerArrive({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Image.asset(
        'assets/imgs/img_new_summer_arrival.png',
        width: 334.w,
        height: 104.h,
      ),
    );
  }
}
